package com.mx.web.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mx.web.model.Article;
import com.mx.web.model.Pagination;
import com.mx.web.model.ResInfo;
import com.mx.web.model.User;
import com.mx.web.service.ArticleService;

@RequestMapping("/article")
@Controller
public class ArticleController {

	// private static final Logger logger =
	// LoggerFactory.getLogger(ArticleController.class);

	@Autowired
	private ArticleService articleService;
	ResInfo resInfo = new ResInfo();

	@ResponseBody
	@RequestMapping(value = "/push", method = RequestMethod.POST)
	public ResInfo push(Article article) {
		UserDetails userDetails = (UserDetails) SecurityContextHolder
				.getContext().getAuthentication().getPrincipal();
		try {
			article.setUser(new User(userDetails.getUsername()));
			article.setCreateTime(new Date());
			articleService.push(article);
			resInfo.setResult(true);
			resInfo.setResultInfo("文章保存成功!");
		} catch (Exception e) {
			e.printStackTrace();
			resInfo.setResult(false);
			resInfo.setResultInfo("文章保存失败!");
		}
		return resInfo;
	}

	@ResponseBody
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public Article load(@PathVariable String id) {
		Article article = null;
		try {
			article = articleService.load(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return article;
	}

	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "/list/{page}")
	public List<Article> list(HttpSession session, @PathVariable int page) {

		Pagination<Article> p = null;
		try {
			p = articleService.list(page);
			resInfo.setResult(true);
			resInfo.setResultInfo("文章列表获取成功!");
			resInfo.put("page", p);
		} catch (Exception e) {
			e.printStackTrace();
			resInfo.setResult(false);
			resInfo.setResultInfo("文章列表获取失败!");
		}
		return (List<Article>) p.getItems();
	}
}